import numpy as np


def get_coefficient_list(x, y, n):
    """
    最小二乘法
    :param x: 自变量
    :param y: 因变量
    :param n: 多项式参数个数
    :return:
    """
    x_list = []
    y_list = []
    for i in x:
        x_c = []
        for c in range(n):
            if c is 0:
                x_c.append(1)
            else:
                x_c.append(i**c)
        x_list.append(x_c)
    for i in y:
        y_list.append([i])
    x_m = np.matrix(x_list)
    y_m = np.matrix(y_list)
    r_m = (x_m.I * y_m).T
    p = r_m.tolist()
    return p[0][::-1]


if __name__ == "__main__":
    x = [1, 2, 3, 5, 9]
    y = [0.9, 1.8, 3.2, 5.1, 8.5]
    print("Fitting Param: ", get_coefficient_list(x, y, 2))